import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken, removeToken } from '@/utils/auth'
import { isHttp, isPathMatch } from '@/utils/validate'
import useUserStore from '@/store/modules/user'

NProgress.configure({ showSpinner: false })

const whiteList = ['/index','/login', '/register', '/smsContent','/cmsContent', '/forgetPassword','/aboutUs','/vip','/thesisList','/jobTitleType','/moreThesis','/thesisDownload/:id','/thesisDownload','/thesisDownload/','/thesisDownload/*']

const isWhiteList = (path) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  // removeToken()
  if(!useUserStore().navigateList.length) {
        useUserStore().getWebsiteInfo()
      }
  if (getToken()) {
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else if (isWhiteList(to.path)) {
      if (!useUserStore().customerUid) {
        useUserStore().getInfo().then((res) => {
          next()
          NProgress.done()
        })
      }
      next()
    } else {
      if (!useUserStore().customerUid) {
        useUserStore().getInfo().then((res) => {
          next()
          NProgress.done()
        }).catch(err => {
          useUserStore().logOut().then(() => {
            ElMessage.error(err)
            next({ path: '/' })
          })
        })
      }else {
        next()
        NProgress.done()
      }
    }
  } else {
    // 没有token
    if (isWhiteList(to.path)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
